<?php

class ProfessionController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','ajaxGetRegions','ajaxGetRegionsSearch','searchIndex'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete','admin','ajaxRate','deleteComment'),
				'users'=>array('@'),
			),
			/* array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			), */
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$profession=$this->loadModel($id);
		$comment=$this->newComment($profession);
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'comment'=>$comment,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Profession;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Profession'])) {
			$model->attributes=$_POST['Profession'];
			$model->created_date = new CDbExpression('NOW()');
			$model->created_by = Yii::app()->user->id;
			$model->country_id=1;
			if($model->validate()){
				if($model->mobile!=null && $model->mobile!=''){
					$prof=Profession::model()->find('professionType_id=:professionType_id and mobile=:mobile', array(':professionType_id'=>$model->professionType_id,':mobile'=>$model->mobile));
					if($prof!=null){
						$model->addError('mobile',Yii::t('profession_messages','profession.mobile.unique.error'));
					}else if ($model->save()) {
						$this->redirect(array('view','id'=>$model->id));
						}
				}
			else if ($model->save()) {
				$this->redirect(array('view','id'=>$model->id));
			}
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		if($model->created_by==Yii::app()->user->id){
			
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Profession'])) {
			$model->attributes=$_POST['Profession'];
			if ($model->save()) {
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
		
		}else{
			throw new CHttpException(403,"You are not allowed to access this page.");
		}
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if (Yii::app()->request->isPostRequest) {
			$rates = Rate::model()->findAllByAttributes(array('professionid'=>$id));
			foreach ($rates as $rateObj){
				$rateObj->delete();
			}
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax'])) {
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			}
		} else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Profession', array(
					'pagination'=>array(
							'pageSize'=>10,
					),
			));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	public function actionSearchIndex()
	{
		if (isset(Yii::app()->session['model'])) {
			$model=Yii::app()->session['model'];
			//unset(Yii::app()->session['model']);
			$criteria=new CDbCriteria;
				
			$criteria->compare('name',$model->name,true);
			$criteria->compare('mobile',$model->mobile,true);
			$criteria->compare('email',$model->email,true);
			$criteria->compare('professionType_id',$model->professionType_id);
			$criteria->compare('state_id',$model->state_id);
			$criteria->compare('region_id',$model->region_id);
	
			$dataProvider = new CActiveDataProvider('Profession', array(
					'criteria'=>$criteria,
					'pagination'=>array(
							'pageSize'=>10,
					),
			));
	
		}else {
			$dataProvider=new CActiveDataProvider('Profession');
		}
		$this->render('index',array(
				'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Profession('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Profession'])) {
			$model->attributes=$_GET['Profession'];
		}

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	

	public function actionAjaxGetRegions(){
	
		$data=Region::model()->findAll('state_id=:state_id',
				array(':state_id'=>(int) $_POST['state_id']));
	
		$data=CHtml::listData($data,'id','nameLocalized');
		echo CHtml::tag('option',
				array('value'=>''),Yii::t('default','choose.from.list'),true);
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',
					array('value'=>$value),CHtml::encode($name),true);
		}
	}
	
	
	public function actionAjaxGetRegionsSearch(){
	
		$data=Region::model()->findAll('state_id=:state_id',
				array(':state_id'=>(int) $_POST['state_id']));
	
		$data=CHtml::listData($data,'id','nameLocalized');
		echo CHtml::tag('option',
				array('value'=>''),Yii::t('profession_messages','search.all.regions'),true);
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',
					array('value'=>$value),CHtml::encode($name),true);
		}
	}
	
	public function actionAjaxRate(){
		if (isset($_GET['score'])&&isset($_GET['professionId'])){
			$score =  $_GET['score']!='null'?$_GET['score']:0;
			$professionId=$_GET['professionId'];
			$rateObj=Rate::model()->find('professionid=:professionId and userid=:userid', array(':professionId'=>$professionId,':userid'=>Yii::app()->user->id));
			if($rateObj!=null){
				if($score==0){
					$rateObj->delete();
				}else{
					$rateObj->rate=$score;
					$rateObj->save();
				}
			}else if($score >0){
				$rateObj = new Rate();
				$rateObj->userid = Yii::app()->user->id;
				$rateObj->professionid = $professionId;
				$rateObj->rate = $score;
				$rateObj->save();
			}
			
			Yii::app()->db->createCommand("update tbl_profession set avgRate =( SELECT CAST(SUM( rate )/COUNT( id ) as UNSIGNED) FROM tbl_rate WHERE professionid = ".$professionId.") WHERE id =".$professionId)->execute();
			
			echo $score;
		}
		
	}
	
	protected function newComment($profession)
	{
		$comment=new Comment;
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($comment);
			Yii::app()->end();
		}
		if(isset($_POST['Comment']))
		{
			$comment->attributes=$_POST['Comment'];
			if($profession->addComment($comment))
			{
				if($comment->status==Comment::STATUS_PENDING)
					Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
				$this->refresh();
			}
		}
		return $comment;
	}
	
	public function actionDeleteComment(){

		if (isset($_GET['commentId']) && isset($_GET['professionId']) ){
		$comment = Comment::model()->findbyPk($_GET['commentId']);
		if($comment != null && ($comment->userid == Yii::app()->user->id || Yii::app()->user->role=='admin')){
			$comment->delete();
		}
		}
		
		$this->redirect(array('view','id'=>$_GET['professionId']));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Profession the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Profession::model()->findByPk($id);
		if ($model===null) {
			throw new CHttpException(404,'The requested page does not exist.');
		}
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Profession $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if (isset($_POST['ajax']) && $_POST['ajax']==='profession-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}